import React, { useEffect, useState } from 'react';
import { Avatar, Divider, List, Skeleton } from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import api from '../api/axios'
import { useNavigate } from 'react-router-dom';
interface DataType {
  gender?: string;
  name?: string;
  email?: string;
  avatar?: string;
  id?: string;
}
const App: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DataType[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10)
  const loadMoreData = async () => {
    if (loading) {
      return;
    }
    setLoading(true);
    try {
      const res = await api.get('/article/list', { params: { page, pageSize } })
      const { status, data } = res
      if (status === 200) {
        setData((prevData) => [...prevData, ...data.rows])
        setLoading(false)
        setPage((prevPage) => prevPage + 1)
      }
    } catch (error) {
      setLoading(false)
      console.error('Error', error)
    }
  };
  useEffect(() => {
    loadMoreData();
  }, []);
  const godetail = (id)=>{
    navigate(`/detail/${id}`)
  }
  return (
    <div
      id="scrollableDiv"
      style={{
        height: 600,
        overflow: 'auto',
        padding: '0 16px',
        border: '1px solid rgba(140, 140, 140, 0.35)',
      }}
    >
      <InfiniteScroll
        dataLength={data.length}
        next={loadMoreData}
        hasMore={data.length < 50}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain>没有更多内容了</Divider>}
        scrollableTarget="scrollableDiv"
      >
        <List
          dataSource={data}
          renderItem={(item,index) => (
            <List.Item key={index} onClick={()=>godetail(item.id)}>
              <List.Item.Meta
                avatar={<Avatar src={`https://picsum.photos/150/150?random=${item.id}`} />}
                title={item.title}
                description={item.content}
              />
            </List.Item>
          )}
        />
      </InfiniteScroll>
    </div>
  );
};

export default App;